<script lang="ts" setup>
import { defineComponent, ref } from 'vue'
import {
  deleteProcessDefinition, getProcessDefinitionList,
  getProcessDefinitionXml, saveProcessDefinition,
  uploadBpmnFile
} from '@/api/activiti/ProcessDefinition'
import { Message } from '@arco-design/web-vue'
import { IconUpload } from '@arco-design/web-vue/es/icon'
import { startProcessInstance, StartProcessInstanceParams } from '@/api/activiti/ProcessInstance'
import BpmnDemo from '@/views/workflow/components/bpmn.vue'

defineComponent({
  name: 'Definition'
})

const bpmnDemo = ref(null)
const uploadVisible = ref(false)
// 文件列表
const fileLists = ref([])
// 表格
const definitionList = ref([])
// 流程实例key
const startInstance = ref(false)
// 分页
const queryParams = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 提交数据
const form = ref<StartProcessInstanceParams>({})

/**
 * 校验
 */
async function beforeUpload(file) {
  try {
    await bpmnDemo.value.beforeUpload(file)
    return true
  } catch (e) {
    Message.error(e.message)
    return false
  }
}

/**
 * 获取列表
 */
async function getList() {
  const { data: { data, total } } = await getProcessDefinitionList(queryParams.value)
  definitionList.value = data
  queryParams.value.total = total
}

// 上传提交
async function submitFile() {
  const formData = new FormData()
  fileLists.value.forEach(item => formData.append('files', item.file))
  const { data } = await uploadBpmnFile(formData)
  if (data) {
    await getList()
    Message.success('上传成功')
    uploadVisible.value = false
  }
}

/**
 * 分页更改
 */
function onPageChange(page) {
  queryParams.value.current = page
  getList()
}

/**
 * 查看 BPMMN
 */
async function loadXml(record) {
  const xmlStr = await getProcessDefinitionXml(record)
  if (xmlStr) {
    bpmnDemo.value.xml = xmlStr.msg
    bpmnDemo.value.visible = true
  } else {
    Message.error('获取流程定义失败')
  }
}

/**
 * 启动流程实例前
 */
function submitBefore(key) {
  form.value.key = key
  startInstance.value = true
}

/**
 * 启动流程实例
 */
async function handleStart(done) {
  const { data } = await startProcessInstance(form.value)
  if (data) {
    Message.success('启动成功')
    done()
  }
}

/**
 * 删除流程定义
 */
async function handleDelete(deploymentId) {
  const { data } = await deleteProcessDefinition(deploymentId)
  if (data) {
    Message.success('删除成功')
    await getList()
  }
}

/**
 * 在线提交BPMN数据
 */
async function handleSubmit(xmlStr, name) {
  const { data } = await saveProcessDefinition({ xml: xmlStr, name })
  if (data) {
    Message.success('绘制成功')
    bpmnDemo.value.visible = false
  }
}

getList()

</script>

<template>
  <div class="container">
    <Breadcrumb :items="['menu.workflow', 'menu.workflow.definition']" />
    <a-card class="general-card" :title="$t('menu.workflow.definition')">
      <!--  查询  -->
      <!--      <a-row>
              <a-col :flex="1">
                <a-form :model="formModel">
                  <a-row :gutter="16">
                    <a-col :span="8">
                      <a-form-item field="name" :label="$t('user.name')">
                        <a-input
                          v-model="formModel.name"
                          :placeholder="$t('user.name.placeholder')"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :span="8">
                      <a-form-item field="phonenumber" :label="$t('user.phonenumber')">
                        <a-input-number
                          v-model="formModel.phonenumber"
                          :placeholder="$t('user.phonenumber.placeholder')"
                        />
                      </a-form-item>
                    </a-col>
                    <a-col :span="8">
                      <a-form-item field="status" :label="$t('user.status')">
                        <a-select
                          v-model="formModel.status" allow-clear
                          :placeholder="$t('user.status.placeholder')">
                          <a-option label="正常" :value="0" />
                          <a-option label="停用" :value="1" />
                        </a-select>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-form>
              </a-col>
            </a-row>-->
      <a-divider style="margin-top: 0" />
      <!--  新建    -->
      <a-row style="margin-bottom: 16px">
        <a-col :span="3">
          <a-space>
            <a-button type="primary" @click="bpmnDemo.visible = true">
              <template #icon>
                <icon-plus />
              </template>
              在线绘制流程
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="3">
          <a-button type="primary" @click="uploadVisible = true">
            <template #icon>
              <IconUpload />
            </template>
            上传Bpmn
          </a-button>
        </a-col>
      </a-row>

      <BpmnDemo ref="bpmnDemo" @get-xml="handleSubmit" />

      <a-modal v-model:visible="uploadVisible" title="上传Bpmn" @before-open="fileLists = []">
        <a-upload
          v-model:file-list="fileLists" :auto-upload="false" :limit="5"
          :show-retry-button="false" @before-upload="beforeUpload">
          <template #upload-button>
            <a-button type="primary">
              上传 Bpmn
            </a-button>
          </template>
        </a-upload>
        <template #footer>
          <a-button type="primary" @click="submitFile">提交</a-button>
        </template>
      </a-modal>

      <a-modal v-model:visible="startInstance" title="启动流程实例" @before-ok="handleStart" @close="form = {}">
        <a-form :model="form">
          <a-form-item field="name" label="名称">
            <a-input v-model="form.name" />
          </a-form-item>
        </a-form>
      </a-modal>

      <a-table :data="definitionList" :pagination="queryParams" @page-change="onPageChange">
        <template #columns>
          <a-table-column title="编号" align="center" data-index="deploymentId" />
          <a-table-column title="名称" align="center" data-index="name" />
          <a-table-column title="文件名" align="center" data-index="resourceName" />
          <a-table-column title="KEY" align="center" data-index="key" />
          <a-table-column title="版本" align="center" data-index="version" />
          <a-table-column title="操作" align="center">
            <template #cell="{record}">
              <a-space>
                <a-button type="primary" size="mini" @click="loadXml(record)">
                  查看
                </a-button>
                <a-button type="primary" size="mini" @click="submitBefore(record.key)">
                  启动
                </a-button>
                <a-popconfirm content="确认要删除吗" type="error" @ok="handleDelete(record.deploymentId)">
                  <a-button type="primary" size="mini">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

:deep(.arco-upload-progress) {
  display: none;
}

</style>